﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using SuperQuiz.Model;
using System.Runtime.Serialization;
using System.Text;
using Microsoft.Phone.Shell;

namespace SuperQuiz
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();

            //Controller.Instance.Init();

            

            this.DataContext = Controller.Instance.Quiz;

            MainListBox.ItemsSource = Controller.Instance.Quiz.Tests;

            


            //List<UpdateTopic> list;

            //MemoryStream m = new MemoryStream(1024);

            //list = new List<UpdateTopic>();

            //list.Add(new UpdateTopic() { Name = "jkjklj", URL = "Kjkljlk" });
            //list.Add(new UpdateTopic() { Name = "111", URL = "Kjkljlk" });
            //DataContractSerializer serializer = new DataContractSerializer(typeof(List<UpdateTopic>));

            //serializer.WriteObject(m, list);

            //string t = Encoding.UTF8.GetString(m.GetBuffer(), 0, (int) m.Length);



        }



        private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (MainListBox.SelectedIndex == -1)
                return;

            // Navigate to the new page
            NavigationService.Navigate(new Uri("/QuestionPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative));
            PhoneApplicationService.Current.State["CurrentTest"] = ((KeyValuePair<string, Test>)MainListBox.SelectedItem).Value;

            // Reset selected index to -1 (no selection)
            MainListBox.SelectedIndex = -1;
        }


        private void downloadButton_Click_1(object sender, RoutedEventArgs e)
        {
            String url = textBox1.Text;
            WebClient wc = new WebClient();
            string fileName = System.IO.Path.GetFileName(url);
            wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
            wc.OpenReadAsync(new System.Uri(url, System.UriKind.RelativeOrAbsolute));
        }


        void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {

            Parser.Parser parser = new Parser.Parser(e.Result);

            foreach (Test t in parser.Tests.Values)
            {
                //if (Controller.Instance.Quiz.Tests.ContainsKey(t.Name))
                //{
                //}
                Controller.Instance.Quiz.Tests[t.Name] = t;
            }
            MainListBox.ItemsSource = null;
            MainListBox.ItemsSource = Controller.Instance.Quiz.Tests;



            //using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            //{
            //    if (store.FileExists("abc.txt"))
            //    {
            //        store.DeleteFile("abc.txt");
            //    }

            //    var fs = new IsolatedStorageFileStream("abc.txt", FileMode.Create, store);
            //    byte[] stream = new byte[e.Result.Length];
            //    e.Result.Read(stream, 0, (int)stream.Length);
            //    fs.Write(stream, 0, stream.Length);
            //    fs.Flush();
            //    fs.Close();
            //}

            //string test = System.Text.Encoding.UTF8.GetString(stream, 0, stream.Length);
            //Parser.Parser parser = new Parser.Parser("abc.txt");
            ////listBox1.Items.Clear();
            //foreach (Test t in parser.Tests.Values)
            //{
            //    listBox1.Items.Add(t.Name);
            //}
        }

        void wc_OpenReadCompleted2(object sender, OpenReadCompletedEventArgs e)
        {
            List<UpdateTopic> list;

            DataContractSerializer serializer = new DataContractSerializer(typeof(List<UpdateTopic>));
            
            list = (List<UpdateTopic>)serializer.ReadObject(e.Result);

            listBox1.ItemsSource = list;
            listBox1.DisplayMemberPath = "Name";
             
            //foreach (UpdateTopic topic in list)
            //{
            //    listBox1.Items.Add(topic.Name);
            //}
        }

        private void getUpdates_Click(object sender, RoutedEventArgs e)
        {
            //String url = //"http://127.0.0.1:8888/topicos.xml";
            String url = textBox1.Text;
            WebClient wc = new WebClient();
            string fileName = System.IO.Path.GetFileName(url);
            wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted2);
            wc.OpenReadAsync(new System.Uri(url, System.UriKind.RelativeOrAbsolute));
        }

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listBox1.SelectedItem != null)
            {
                UpdateTopic topic = (UpdateTopic) listBox1.SelectedItem;
                MessageBox.Show(topic.URL);

                WebClient wc = new WebClient();
                wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
                wc.OpenReadAsync(new System.Uri(topic.URL, System.UriKind.RelativeOrAbsolute));

            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            //this.DataContext = Controller.Instance.Quiz;
            MainListBox.ItemsSource = null;
            MainListBox.ItemsSource = Controller.Instance.Quiz.Tests;

            base.OnNavigatedTo(e);
        }
    }
}